intlengthOfLongestSubstring(string s) { int m[256];//字符共有256个,ascii码为i的字符最近位置为m[i] for (int i = 0; i < 256; i++) m[i] = -1; int res = 0;//最大的长度 int left = 0;//左端点的编号 for (int rg = 0; rg < s.size(); ++rg) { if (res == 0 || m[s[rg]] < left) {//还未开始移动,或在当前子字符串中无字母s[rg] res = res > rg - left + 1 ? res : rg - left + 1; m[s[rg]] = rg; } else {//当前子字符串中存在字母s[rg] left = m[s[rg]] + 1; m[s[rg]] = rg; } } return res; }
对特殊的字符串进行测试:
1 2 3 4 5 6 7
string a = "abcabcbb"; string b = "bbbbb"; string c = "pwwkew"; string d = "122*hfks2ilnuibin"; string e = "au"; cout << lengthOfLongestSubstring(a) << " " << lengthOfLongestSubstring(b) << " " << lengthOfLongestSubstring(c) <<" "<< lengthOfLongestSubstring(d) << " " << lengthOfLongestSubstring(e) << endl;